{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%matplotlib inline\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "import seaborn as sns"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.datasets._samples_generator import make_blobs\n",
    "X,y = make_blobs(n_samples=50, centers=2, random_state=0, cluster_std=0.6)\n",
    "plt.scatter(X[:,0],X[:,1], c=y, s=50, cmap='autumn')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "xfit = np.linspace(-1,3.5)\n",
    "plt.scatter(X[:,0],X[:,1],c=y,s=50,cmap='autumn')\n",
    "plt.plot([0.6],[2.1], 'x',color='red', markeredgewidth=2, markersize=10)\n",
    "\n",
    "for m,b in [(1,0.65),(0.5,1.6),(-0.2,2.9)]:\n",
    "    plt.plot(xfit, m*xfit+b,'-k')\n",
    "\n",
    "plt.xlim(-1,3.5)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "xfit = np.linspace(-1,3.5)\n",
    "plt.scatter(X[:,0],X[:,1],c=y, s=50,cmap='autumn')\n",
    "for m,b,d in [(1, 0.65, 0.33), (0.5, 1.6, 0.55), (-0.2, 2.9, 0.2)]:\n",
    "    yfit = m * xfit + b\n",
    "    plt.plot(xfit, yfit, '-k')\n",
    "    plt.fill_between(xfit, yfit-d, yfit+d, edgecolor='none', color='#AAAAAA', alpha=0.5)\n",
    "plt.xlim(-1,3.5)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.svm import SVC # \"Support vector classifier\"\n",
    "model = SVC(kernel='linear', C=1E10)\n",
    "model.fit(X, y)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def plot_svc_decision_function(model, ax=None, plot_support=True):\n",
    "    \"\"\"Plot the decision function for a two-dimensional SVC\"\"\"\n",
    "    if ax is None:\n",
    "        ax = plt.gca()\n",
    "    xlim = ax.get_xlim()\n",
    "    ylim = ax.get_ylim()\n",
    "    # create grid to evaluate model\n",
    "    x = np.linspace(xlim[0], xlim[1], 30)\n",
    "    y = np.linspace(ylim[0], ylim[1], 30)\n",
    "    Y, X = np.meshgrid(y, x)\n",
    "    xy = np.vstack([X.ravel(), Y.ravel()]).T\n",
    "    P = model.decision_function(xy).reshape(X.shape)\n",
    "    # plot decision boundary and margins\n",
    "    ax.contour(X, Y, P, colors='k', levels=[-1, 0, 1], alpha=0.5, linestyles=['--', '-', '--'])\n",
    "    # plot support vectors\n",
    "    if plot_support:\n",
    "        ax.scatter(model.support_vectors_[:, 0], model.support_vectors_[:, 1], s=300, linewidth=1, edgecolor='black', facecolors='none')\n",
    "    ax.set_xlim(xlim)\n",
    "    ax.set_ylim(ylim)\n",
    "    \n",
    "plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='autumn')\n",
    "plot_svc_decision_function(model)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def plot_svm(N=10, ax=None):\n",
    "    X,y = make_blobs(n_samples=200, centers=2, random_state=0, cluster_std=0.6)\n",
    "\n",
    "    X=X[:N]\n",
    "    y=y[:N]\n",
    "\n",
    "    model = SVC(kernel=\"linear\",C=1E10)\n",
    "    model.fit(X,y)\n",
    "    ax = ax or plt.gca()\n",
    "    ax.scatter(X[:,0],X[:,1],c=y,s=50,cmap='autumn')\n",
    "    ax.set_xlim(-1,4)\n",
    "    ax.set_ylim(-1,6)\n",
    "    plot_svc_decision_function(model, ax)\n",
    "\n",
    "fig, ax = plt.subplots(1,2,figsize=(16,6))\n",
    "fig.subplots_adjust(left=0.0625, right=0.95, wspace=0.1)\n",
    "for axi, N in zip(ax, [60,120]):\n",
    "    plot_svm(N,axi)\n",
    "    axi.set_title(\"N={0}\".format(N))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.datasets._samples_generator import make_circles\n",
    "\n",
    "X,y = make_circles(100, factor=0.1, noise=0.1)\n",
    "clf = SVC(kernel='linear').fit(X,y)\n",
    "plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='autumn')\n",
    "plot_svc_decision_function(clf, plot_support=False);"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from mpl_toolkits import mplot3d\n",
    "from ipywidgets import interact, fixed\n",
    "r = np.exp(-(X ** 2).sum(1))\n",
    "def plot_3D(elev=30, azim=30, X=X,y=y):\n",
    "    ax = plt.subplot(projection='3d')\n",
    "    ax.scatter3D(X[:,0],X[:,1],r, c=y, s=50, cmap='autumn')\n",
    "    ax.view_init(elev=elev, azim=azim)\n",
    "    ax.set_xlabel('x')\n",
    "    ax.set_ylabel('y')\n",
    "    ax.set_zlabel('r')\n",
    "\n",
    "interact(plot_3D, elev=[-90,30, 90], azip=(-180, 180),X=fixed(X), y=fixed(y));    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "clf = SVC(kernel='rbf', C=1E6)\n",
    "clf.fit(X, y)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='autumn')\n",
    "plot_svc_decision_function(clf)\n",
    "plt.scatter(clf.support_vectors_[:, 0], clf.support_vectors_[:, 1], s=300, lw=1, facecolors='none');"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "X, y = make_blobs(n_samples=100, centers=2, random_state=0, cluster_std=1.2)\n",
    "plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='autumn')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "X, y = make_blobs(n_samples=100, centers=2,random_state=0, cluster_std=0.8)\n",
    "fig, ax = plt.subplots(1, 2, figsize=(16, 6))\n",
    "fig.subplots_adjust(left=0.0625, right=0.95, wspace=0.1)\n",
    "for axi, C in zip(ax, [10.0, 0.1]):\n",
    "    model = SVC(kernel='linear', C=C).fit(X, y)\n",
    "    axi.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='autumn')\n",
    "    plot_svc_decision_function(model, axi)\n",
    "    axi.scatter(model.support_vectors_[:, 0],model.support_vectors_[:, 1],s=300, lw=1, facecolors='none')\n",
    "    axi.set_title('C = {0:.1f}'.format(C), size=14)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.datasets import fetch_lfw_people\n",
    "faces = fetch_lfw_people(min_faces_per_person=60)\n",
    "print(faces.target_names)\n",
    "print(faces.images.shape)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fig, ax = plt.subplots(3, 5)\n",
    "for i, axi in enumerate(ax.flat):\n",
    "    axi.imshow(faces.images[i], cmap='bone')\n",
    "    axi.set(xticks=[], yticks=[], xlabel=faces.target_names[faces.target[i]])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.svm import SVC\n",
    "from sklearn.decomposition import PCA\n",
    "from sklearn.pipeline import make_pipeline\n",
    "\n",
    "pca = PCA(n_components=150, whiten=True, random_state=42,svd_solver='randomized')\n",
    "svc = SVC(kernel='rbf', class_weight='balanced')\n",
    "model = make_pipeline(pca,svc)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import train_test_split\n",
    "Xtrain, Xtest, ytrain, ytest = train_test_split(faces.data, faces.target, random_state=42)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection  import GridSearchCV\n",
    "param_grid = {'svc__C': [1, 5, 10, 50], 'svc__gamma': [0.0001, 0.0005, 0.001, 0.005]}\n",
    "grid = GridSearchCV(model, param_grid)\n",
    "%time grid.fit(Xtrain, ytrain)\n",
    "print(grid.best_params_ )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "model = grid.best_estimator_\n",
    "yfit = model.predict(Xtest)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fig, ax = plt.subplots(4, 6)\n",
    "for i, axi in enumerate(ax.flat):\n",
    "    axi.imshow(Xtest[i].reshape(62, 47), cmap='bone')\n",
    "    axi.set(xticks=[], yticks=[])\n",
    "    axi.set_ylabel(faces.target_names[yfit[i]].split()[-1], color='black' if yfit[i] == ytest[i] else 'red')\n",
    "fig.suptitle('Predicted Names; Incorrect Labels in Red', size=14)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.metrics import classification_report\n",
    "print(classification_report(ytest, yfit,target_names=faces.target_names))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.metrics import confusion_matrix\n",
    "mat = confusion_matrix(ytest, yfit)\n",
    "sns.heatmap(mat.T, square=True, annot=True, fmt='d', cbar=False, xticklabels=faces.target_names, yticklabels=faces.target_names)\n",
    "plt.xlabel('true label')\n",
    "plt.ylabel('predicted label')"
   ]
  }
 ],
 "metadata": {
  "interpreter": {
   "hash": "e21935a792cabaadabb39e077efde3aadff814271e124eae6fb74a8aae0f5081"
  },
  "kernelspec": {
   "display_name": "Python 3.10.5 64-bit",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.5"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
